#include "logindlg.h"
#include "ui_logindlg.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QUrlQuery>
#include <QMessageBox>
#include <QDebug>
#include "student.h"
#include "page_mainwindow.h"
#include "admin.h"
#include "dbmanager.h"

logindlg::logindlg(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::logindlg)
    , mainWindow(nullptr)
    , admin(nullptr)
{
    ui->setupUi(this);

    setWindowTitle("登录宿舍系统");
    ui->radioStudent->setChecked(true);
    ui->stackedWidget->setCurrentIndex(0); // 初始显示学生登录页面

    connect(ui->lineEdit_stupd, &QLineEdit::returnPressed, this, &logindlg::on_btnLogin_clicked);
    connect(ui->lineEdit_adminpd, &QLineEdit::returnPressed, this, &logindlg::on_btnLogin_clicked);
    connect(ui->lineEdit_dormpd, &QLineEdit::returnPressed, this, &logindlg::on_btnLogin_clicked);
}

logindlg::~logindlg()
{
    delete ui;
}

void logindlg::on_radioStudent_toggled(bool checked) {
    if (checked) {
        ui->stackedWidget->setCurrentIndex(0); // 学生登录页面索引0
    }
}

void logindlg::on_radioAdmin_toggled(bool checked) {
    if (checked) {
        ui->stackedWidget->setCurrentIndex(1); // 管理员登录页面索引1
    }
}

void logindlg::on_radioDormManager_toggled(bool checked) {
    if (checked) {
        ui->stackedWidget->setCurrentIndex(2); // 宿管登录页面索引2
    }
}

int logindlg::getSelectedRole() const {
    if (ui->radioStudent->isChecked()) return 0;
    if (ui->radioAdmin->isChecked()) return 1;
    if (ui->radioDormManager->isChecked()) return 2;
    return -1;
}

QString logindlg::getUserId() const {
    int role = getSelectedRole();
    switch (role) {
    case 0: return ui->lineEdit_stuid->text();
    case 1: return ui->lineEdit_adminid->text();
    case 2: return ui->lineEdit_dormid->text();
    default: return "";
    }
}

void logindlg::on_btnLogin_clicked()
{
    int role = getSelectedRole();
    QString userId = getUserId();

    QSqlDatabase db = DBManager::instance()->getDatabase();

    if (db.open()) {
    } else {
        QMessageBox::critical(this, "连接失败",
                              "数据库连接错误：" + db.lastError().text());
        return; // 连接失败时直接返回
    }

    QString tableName, errorMsg, passwordField;
    switch (role) {
    case 0:
        tableName = "student";
        errorMsg = "学生账号";
        passwordField = "stu_password";
        break;
    case 1:
        tableName = "admin";
        errorMsg = "管理员账号";
        passwordField = "admin_password";
        break;
    case 2:
        tableName = "dormmanager";
        errorMsg = "宿管账号";
        passwordField = "login_password";
        break;
    default:
        db.close();
        return;
    }

    QString password = "";
    switch (role) {
    case 0: password = ui->page_stulogin->findChild<QLineEdit*>("lineEdit_stupd")->text(); break;
    case 1: password = ui->page_adminlogin->findChild<QLineEdit*>("lineEdit_adminpd")->text(); break;
    case 2: password = ui->page_dorm->findChild<QLineEdit*>("lineEdit_dormpd")->text(); break;
    }

    QSqlQuery query(db);
    query.prepare(QString("SELECT * FROM %1 WHERE %2 = :id AND %3 = :password")
                      .arg(tableName, role == 0? "student_id" : role == 1? "admin_id" : "manager_id", passwordField));
    query.bindValue(":id", userId);
    query.bindValue(":password", password);

    if (query.exec() && query.next()) {
        QMessageBox::information(this, "成功", "登录成功！");
        if (role == 0) {
            student studentPage;
            studentPage.setUserId(userId);
            this->hide();
            studentPage.exec();
        }else if (role == 1) {  // 管理员登录成功
            if (!admin) {
                admin = new Admin(this);  // 创建管理员主窗口
            }
            this->hide();  // 隐藏登录窗口
            admin->show();  // 显示管理员主窗口
        }else if (role == 2) {  // 舍管登录成功
            if (!mainWindow) {
                mainWindow = new MainWindow(this);  // 创建并指定父对象
            }
            this->hide();  // 隐藏登录窗口
            mainWindow->show();  // 显示主窗口
        }
    } else {
        QMessageBox::warning(this, "失败",
                             QString("%1不存在或密码错误").arg(errorMsg));
    }
    db.close(); // 关闭连接
}

void logindlg::on_btnCancel_clicked()
{
    close();
}
